﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using fNbt;

namespace KaorlganSaveCleaner
{
    class Program
    {
        private static string currentDir => Path.GetDirectoryName(Environment.CurrentDirectory);
        private static string backupFolder => Path.Combine(currentDir, "backup");
        
        static void Main(string[] args)
        {
            if (!IsLocationValid()) return;
            Run();
        }

        private static bool IsLocationValid()
        {
            Console.WriteLine(currentDir);
            return currentDir.EndsWith("world");
        }

        private static void Run()
        {
            //BACKUP
            var Date = DateTime.Now.ToString().Replace(":","-").Replace(" ","-");
            var currentBkFolder = Path.Combine(backupFolder, Date);
            if (!Directory.Exists(currentBkFolder)) Directory.CreateDirectory(currentBkFolder);
            List<string> folders = new List<string>() { "DIM1", "DIM-1", "region" };
            foreach (var folderName in folders)
            {
                var folderPath = Path.Combine(currentDir, folderName);
                var bkPath = Path.Combine(currentBkFolder, folderName);
                if(Directory.Exists(folderPath)) Directory.Move(folderPath,bkPath);
            }
            
            var nbtPath = Path.Combine(currentDir, "level.dat");
            var nbtNewPath = Path.Combine(currentBkFolder, "level.dat");
            File.Copy(nbtPath, nbtNewPath);
            
            //SET NEW SEED
            var nbtObj = new NbtFile();
            nbtObj.LoadFromFile(nbtPath);
            var rootTag = nbtObj.RootTag;
            // var currentSeed = rootTag.Get<NbtCompound>("Data").Get<NbtCompound>("WorldGenSettings").Get<NbtLong>("seed").Value;
            rootTag.Get<NbtCompound>("Data").Get<NbtCompound>("WorldGenSettings").Get<NbtLong>("seed").Value =
                GetRandomSeed();
            nbtObj.SaveToFile(nbtPath, NbtCompression.GZip);
        }

        public static long GetRandomSeed()
        {
            Random rnd = new Random();
            var buffer = new byte[8];
            long result = 0;
            do
            {
                rnd.NextBytes(buffer);
                result = BitConverter.ToInt64(buffer, 0);
            } while (result < 1000000000000000000);  // Ensure it's 19 digits
            return result;
        }
    }
}